package com.huisou.basedataservice;

import com.huisou.domain.Microcode;
import com.huisou.orm.HibernateDao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MicrocodeDao extends HibernateDao<Microcode, Integer> {
	
	private static final String		hql	= "SELECT NEW Code(id,name) from Code where parentId=? group by name order by orderNo asc";
	protected Logger				log	= LoggerFactory.getLogger(getClass());
	
	@Resource
	RedisTemplate<String, Object>	redisTemplate;
	@Resource
	private StringRedisTemplate		stringRedisTemplate;
	
	public List<Microcode> queryCodesByPid(Integer pid) {
		String key = RedisConstants.KEY_SYSCODES_LIST + "_" + pid;
		List<Microcode> listCode = null;
		try {
			listCode = (List<Microcode>) redisTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("获取Code列表出错." + e.getMessage());
		}
		if (listCode == null) {
			try {
				listCode = find(hql, pid);
				if (listCode != null && listCode.size() > 0) {
					redisTemplate.opsForValue().set(key, listCode);
				}
			}
			catch (DataAccessException e) {
				log.error("获取Code列表出错.");
			}
		}
		return listCode;
	}
	
	public Microcode getCodeByIdAndPid(Integer id, Integer pid) {
		String key = RedisConstants.KEY_SYSCODES_SIGNLE + "_" + id + "_" + pid;
		Microcode code = null;
		try {
			code = (Microcode) redisTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("获取Code出错." + e.getMessage());
		}
		if (code == null) {
			try {
				code = findUnique(" from Code where parentId = ? and id = ? ", pid, id);
				if (code != null) {
					redisTemplate.opsForValue().set(key, code);
				}
			}
			catch (DataAccessException e) {
				log.error("获取Code出错.");
			}
		}
		return code;
	}
	
	public String getCodeNameById(Integer id) {
		String key = RedisConstants.KEY_SYSCODES_SIGNLE_NAME + "_" + id;
		String codeName = null;
		try {
			codeName = stringRedisTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("获取codeName出错." + e.getMessage());
		}
		if (StringUtils.isBlank(codeName)) {
			try {
				codeName = this.get(id).getName();
				if (StringUtils.isNotBlank(codeName)) {
					stringRedisTemplate.opsForValue().set(key, codeName);
				}
			}
			catch (DataAccessException e) {
				log.error("获取Code出错.");
			}
		}
		return codeName;
	}
	
}
